//
//  TIMGroupDetailVC.m
//  Demo_sdk
//
//  Created by Deli Xia on 2018/7/3.
//  Copyright © 2018年 Deli Xia. All rights reserved.
//

#import "TIMGroupDetailVC.h"
#import "TIMGrpDetailTableViewCell.h"
#import "TIMDemoMacro.h"
#import "Masonry.h"
#import "UIView+Extension.h"
#import "TIMAddGroupVC.h"
#import "TIMManagerGroupVC.h"
#import "TIMModifyGroupNameVC.h"
#import "TIMModifyAnnounceVC.h"

#import "TIMStorageModel.h"
#import "TIMStorageManager.h"
#import "TIMApi.h"
#import "TIMCommon.h"

@interface TIMGroupDetailVC ()<UITableViewDelegate,UITableViewDataSource,UserTableViewCellDelegateColl>

@property (nonatomic, strong) UITableView *grpTableView;
@property (nonatomic, assign) BOOL isShowMore;
@property (nonatomic, assign) BOOL groupOwnerIsSelf;
@property (nonatomic, assign) BOOL groupAdimin;
@property (nonatomic, strong) UIButton *contentButton;
@property (nonatomic, strong) TIMGroupInfo *groupInfo;
@property (nonatomic, strong) TIMUserInfo *currentUser;

@property (nonatomic, strong) NSArray *announceList;
@end

@implementation TIMGroupDetailVC

- (void)viewDidLoad {
    [super viewDidLoad];
    self.groupAdimin = [self.groupInfo.groupOwner isEqualToString:self.currentUser.userID] ? YES : NO ;
    self.groupOwnerIsSelf = [self.groupInfo.groupOwner isEqualToString:self.currentUser.userID] ? YES : NO;
    self.isShowMore = self.groupInfo.usersCount > 43 ? YES : NO;
    self.navigationItem.title = [NSString stringWithFormat:@"群设置(%ld)", self.groupInfo.usersCount];
    [self.view addSubview:self.grpTableView];
    self.view.backgroundColor = UIColor.whiteColor;
    
//    [TIMApi queryGroupAnnounceMentRequestWithGroupId:self.groupInfo.groupID grpUid:self.currentUser.userID grpAnnOp:TIMAnnounceMent_Operation_GrpAnnounceMentGet groupAnnounceContent:nil completion:^(NSError *error) {
//        if (!error) {
//            NSLog(@"查询群公告成功");
//        }
//    }];
    
    [TIMApi queryGroupAnnounceListWithGroupId:self.groupID total:30 announceId:0 success:^(id response) {
        NSLog(@"查询群功能成功");
        self.announceList = (NSArray *)response;
    } completion:^(NSError *error) {
        NSLog(@"查询群公告失败");
    }];
    
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark - TableviewDelegate
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 6;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    switch (section) {
        case 1:
            return self.isShowMore ? 1 : 0;
            break;
        case 2:
            return self.groupAdimin ? 5 : 4;
        case 3:
            return 2;
        case 5:
            return self.groupOwnerIsSelf ? 1 : 0;
            break;
        default:
            return 1;
            break;
    }
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    if (indexPath.section == 0) {
        NSInteger tem = (self.groupInfo.users.count + 2)/5;
        if ((self.groupInfo.users.count + 2)%5 != 0) {
            ++tem;
        }
        return tem * 75 + 20;
    } else if (indexPath.section == 1) {
        return 38;
    } else if (indexPath.section == 2 && indexPath.row == 1) {
        return 38;
    }
    return 44;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    return 2;
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section {
    if (section == 0 || section == 2) {
        return 0.01;
    } else if (section == 5) {
        return 90;
    }
    return 10;
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
    return nil;
}

- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section {
    //viewforFooter
    if (section == 5) {
        static NSString * identy = @"foot";
        UITableViewHeaderFooterView *footerView = [tableView dequeueReusableHeaderFooterViewWithIdentifier:identy];
        if (!footerView) {
            footerView = [[UITableViewHeaderFooterView alloc]initWithReuseIdentifier:identy];
            
            self.contentButton = [[UIButton alloc] initWithFrame:CGRectMake(15, 17, Screen_Width - 30, 44)];
            self.contentButton.titleLabel.font = [UIFont boldSystemFontOfSize:14];
            self.contentButton.backgroundColor = UIColor.redColor;
            [self.contentButton setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
            [self.contentButton addTarget:self action:@selector(buttonClicked) forControlEvents:UIControlEventTouchUpInside];
            [footerView.contentView addSubview:self.contentButton];
            self.contentButton.tag = 100;
        }
        UIButton *contentButton = (UIButton *)[footerView.contentView viewWithTag:100];
        contentButton.y = self.groupOwnerIsSelf ? 17 : 7;
        NSString *strTitle;
        if (self.groupOwnerIsSelf) {
            strTitle = @"解散群组";
        } else {
            strTitle = @"删除并退出";
        }
        [contentButton setTitle:strTitle forState:UIControlStateNormal];
        
        return footerView;
    }
    return nil;
}

// 第一行的增加群成员
-(void)ClickCooRow:(NSInteger)CellRow {
    NSInteger count;
    if (self.groupInfo.usersCount > 43 && self.groupAdimin) {
        count = 43;
    } else if (self.groupInfo.usersCount > 44 && !self.groupAdimin) {
        count = 44;
    } else {
        count = self.groupInfo.usersCount;
    }
    TIMAddGroupVC *vc = [[TIMAddGroupVC alloc] init];
    if (CellRow == count) {
        CATransition* transition = [CATransition animation];
        vc.groupId = self.groupID;
        vc.addGroupType = 1;// 添加
        transition.type = kCATransitionPush;//可更改为其他方式
        transition.subtype = kCATransitionFromTop;//可更改为其他方式
        [self.navigationController.view.layer addAnimation:transition forKey:kCATransition];
        [self.navigationController pushViewController:vc animated:NO];
    }  else if (CellRow > count) {
        CATransition* transition = [CATransition animation];
        vc.groupId = self.groupID;
        vc.addGroupType = 0;// 移除
        transition.type = kCATransitionPush;//可更改为其他方式
        transition.subtype = kCATransitionFromTop;//可更改为其他方式
        [self.navigationController.view.layer addAnimation:transition forKey:kCATransition];
        [self.navigationController pushViewController:vc animated:NO];
    }
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    if (indexPath.section == 0) {
        TIMGroupUserTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"TIMGroupUserTableViewCell"];
        cell.needConut = self.groupInfo.usersCount + 2;
        cell.grpUsers = self.groupInfo.users;
        cell.count = self.groupInfo.usersCount;
        [cell.userCollectionView reloadData];
        cell.userCollectionView.scrollEnabled = NO;
        cell.UserTableViewCellDelegateColl = self;
        return cell;
    } else if (indexPath.section == 1) {
//        TIMGroupShowMoreTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"TIMGroupShowMoreTableViewCell"];
//        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        return nil;
    }
    else if (indexPath.section == 2) {
        NSArray *titleArr = @[@"群聊名称", @"群公告", @"新的群公告", @"群文件", @"群管理"];
        NSArray *detailArr = @[ _groupInfo.groupName.length > 0 ? _groupInfo.groupName : @"未设置",self.groupInfo.grpAnnounceContent.length > 0 ? self.groupInfo.grpAnnounceContent :  @"未设置", @"",@"",@""];
        TIMGrpDetailTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"TIMGrpDetailTableViewCell"];
        cell.isShowQR = NO;
        cell.titleLab.text = titleArr[indexPath.row];
        cell.detailLab.text = detailArr[indexPath.row];
        return cell;
    }
    else if (indexPath.section == 3) {
        NSArray *titleArr = @[@"消息置顶", @"消息免打扰"];
        TIMGroupOperationTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"TIMGroupOperationTableViewCell"];
        cell.titleLab.text = titleArr[indexPath.row];
        if (indexPath.row == 0) {
            TIMConversationInfo *conversation = [[TIMStorageManager sharedStorageManager] getSingleConversionByPartnerID:self.groupID];
            cell.operationSwitch.on = [conversation.stickState isEqualToString:@"YES"] ? YES : NO;
            
            cell.operationBlock = ^(BOOL state) {
                [TIMApi setTopMessageBySessionId:self.groupID isTop:state];
            };
        } else if (indexPath.row == 1) {
            cell.operationSwitch.on = [self.groupInfo.disturb isEqualToString:@"NO"] ? YES : NO;
            cell.operationBlock = ^(BOOL state) {
                [TIMApi personalSetWithSessionId:self.groupID disturb:state isGroup:1 completion:^(NSError *error) {
                    if (!error) { 
                        NSLog(@"免打扰成功");
                    }
                }];
            };
        }
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        return cell;
    } else if (indexPath.section == 4) {
        TIMGrpDetailTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"TIMGrpDetailTableViewCell"];
        cell.isShowQR = NO;
        cell.titleLab.text = @"我在本群的昵称";
        cell.detailLab.text = _groupInfo.myNikeName.length > 0 ? _groupInfo.myNikeName : @"未设置";
        return cell;
    } else {
        TIMGroupOperationTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"TIMGroupOperationTableViewCell"];
        cell.titleLab.text = @"仅限群主及管理员添加成员";
        cell.operationSwitch.on = [self.groupInfo.group_offer_flag isEqualToString:@"YES"] ? YES : NO;
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        return cell;
    }
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    if (indexPath.section == 2) {
        if (indexPath.row == 0) {
            TIMModifyGroupNameVC *vc = [TIMModifyGroupNameVC new];
            vc.groupID = self.groupID;
            [self.navigationController pushViewController:vc animated:YES];
        }
        
        if (indexPath.row == 1) {
            TIMModifyAnnounceVC *vc = [TIMModifyAnnounceVC new];
            vc.groupID = self.groupID;
            [self.navigationController pushViewController:vc animated:YES];
        }
        
        if (indexPath.row == 2) {
            [TIMApi createGroupAnnnounceWithGroupId:self.groupInfo.groupID announceTitle:@"tiele" announceContent:@"text" success:^(id response) {
                NSLog(@"创建群公告成功：%@，",response);
            } completion:^(NSError *error) {
                NSLog(@"创建群公告失败");
            }];
        }
        
        if (indexPath.row == 3) {
            [TIMApi queryGroupFileListWithGroupId:self.groupID totalcount:0 gotcount:0 version:0 success:^(id response) {
                NSLog(@"查询成功：response:%@",response);
                NSArray *info = [[TIMStorageManager sharedStorageManager] getGroupFileByGroupId:self.groupID];
                 NSLog(@"查询成功：info:%@",info);
            } completion:^(NSError *error) {
                NSLog(@"查询失败,erorCode:%ld",error.code);
            }];
            
//            [TIMApi applyForUploadRequestWithGroupId:self.groupID filemd5:@"12345" fileSize:@"123" permoption:@"12" filename:@"te" fileType:@"123" success:^(id response) {
//                NSLog(@"文件申请上传成功,response:%@",response);
//                NSDictionary *dic = (NSDictionary *)response;
//                [TIMApi uploadNotifyRequestWithGroupId:self.groupID fileId:dic[@"fileid"] completion:^(NSError *error) {
//                    if (!error) {
//                        NSLog(@"上传完毕，通知后台");
//                    }
//                }];
//            } failer:^(NSError *error) {
//                NSLog(@"文件申请上传失败");
//            }];
            
          
            
//            [TIMApi deleteFileRequestWithGroupId:self.groupID fileId:@"10M58Q000000Ah3dM4CcMA3eS8meNo6dR8jpNsPoAd3pyp3pCl6pMo600000" completion:^(NSError *error) {
//                if (!error) {
//                    NSLog(@"删除文件成功");
//                }
//            }];
//            [TIMApi applyForDownloadRequestWithGroupid:self.groupID fileId:@"10M58Q000000Ah3dM4CcMA3eS8meNo6dR8jpNsPoAd3pyp3pCl6pMo600000" success:^(id response) {
//                NSLog(@"申请下载,repsonse:%@",response);
//            } completion:^(NSError *error) {
//                 NSLog(@"申请下载");
//            }];
        
        }
        
        if (indexPath.row == 4) {
            TIMManagerGroupVC *vc = [TIMManagerGroupVC new];
            vc.groupID = self.groupID;
            [self.navigationController pushViewController:vc animated:YES];
        }
    }
    
}

- (void)buttonClicked {
//    NSDictionary *dic = [self.announceList firstObject];
  
    // 读取群公告
//    [TIMApi readAnnounceMentRequestWithGroupId:self.groupInfo.groupID announceId:  dic[@"announceId"] success:^(id response) {
//        NSLog(@"读取成功,reaponse:%@",response);
//    } completion:^(NSError *error) {
//        NSLog(@"读取失败");
//    }];
    
    if (self.groupOwnerIsSelf) {
        [TIMApi operateGroupWithGroupId:self.groupID operateUserId:nil MsgOperation:TIMOperateGroupTypeDismissGroup groupMembers:nil GroupName:[self.groupInfo.groupName dataUsingEncoding:NSUTF8StringEncoding] completion:^(NSError *error) {
            if (!error) {
                NSLog(@"-------------xiadeli-------------解散群成功ok");
                dispatch_async(dispatch_get_main_queue(), ^{
                       [self.navigationController popToRootViewControllerAnimated:YES];
                });
            }

        }];
    } else {
        [TIMApi operateGroupWithGroupId:self.groupID operateUserId:nil MsgOperation:TIMOperateGroupTypeExitGroup groupMembers:nil GroupName:[self.groupInfo.groupName dataUsingEncoding:NSUTF8StringEncoding] completion:^(NSError *error) {
            if (!error) {
                 NSLog(@"-------------xiadeli-------------退出群成功");
                dispatch_async(dispatch_get_main_queue(), ^{
                    [self.navigationController popToRootViewControllerAnimated:YES];
                });
            }
        }];
    }
//    NSMutableArray *array = [NSMutableArray array];
//    TIMUserInfo *user = [[TIMStorageManager sharedStorageManager] getCurrentUserInfo];
//    [array addObject:user];
//    [TIMApi operateGroupWithGroupId:self.groupID operateUserId:@"13987878787" MsgOperation:TIMOperateGroupTypeScanCodeOfferGroup groupMembers:array GroupName:[self.groupInfo.groupName dataUsingEncoding:NSUTF8StringEncoding] completion:^(NSError *error) {
//        if (!error) {
//          NSLog(@"-------------xiadeli-------------扫描群成功");
//        }
//    }];
}

#pragma mark - Get

- (TIMGroupInfo *)groupInfo {
    if (!_groupInfo) {
        _groupInfo = [[TIMStorageManager sharedStorageManager] getGroupInfoByGroupID:self.groupID];
    }
    return _groupInfo;
}

- (TIMUserInfo *)currentUser {
    if (!_currentUser) {
        TIMUserInfo *user = [[TIMStorageManager sharedStorageManager] getCurrentUserInfo];
        _currentUser = [[TIMStorageManager sharedStorageManager] getSingleMemberInfoByGroupID:self.groupID friendID:user.userID];
    }
    return _currentUser;
}

- (UITableView *)grpTableView {
    if (!_grpTableView) {
        _grpTableView = [[UITableView alloc] initWithFrame:self.view.frame style:UITableViewStyleGrouped];
        _grpTableView.backgroundColor = UIColor.clearColor;
        _grpTableView.delegate = self;
        _grpTableView.dataSource = self;
        [_grpTableView setBackgroundColor:RGBColor(240, 240, 240)];
        [_grpTableView setSectionIndexColor:[UIColor darkGrayColor]];
        [_grpTableView setSectionIndexBackgroundColor:[UIColor clearColor]];
        _grpTableView.separatorStyle = RGBColor(240, 240, 240);
        _grpTableView.estimatedRowHeight = 0;
        _grpTableView.estimatedSectionHeaderHeight = 0;
        _grpTableView.estimatedSectionFooterHeight = 0;
        [_grpTableView registerClass:[TIMGrpDetailTableViewCell class] forCellReuseIdentifier:@"TIMGrpDetailTableViewCell"];
        [_grpTableView registerClass:[TIMAnnouncementTableViewCell class] forCellReuseIdentifier:@"TIMAnnouncementTableViewCell"];
        [_grpTableView registerClass:[TIMGroupOperationTableViewCell class] forCellReuseIdentifier:@"TIMGroupOperationTableViewCell"];
        [_grpTableView registerClass:[TIMGroupShowMoreTableViewCell class] forCellReuseIdentifier:@"TIMGroupShowMoreTableViewCell"];
        [_grpTableView registerClass:[TIMGroupUserTableViewCell class] forCellReuseIdentifier:@"TIMGroupUserTableViewCell"];
    }
    return _grpTableView;
}
@end
